import './login.scss';

import { useEffect } from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

// 仓库
import { useSelector, useDispatch } from 'react-redux';
import type { StoreState, StoreDispatch } from '../../store';
// 仓库内异步任务
import { toLoginAction } from '../../store/modules/user';

const styles = {
    login: {
        background: `linear-gradient(blue, pink)`,
        width: '100vw',
        height: '100vh',
    },
};
interface loginData {
    username: string;
    password: string;
    remember: string;
}

const Login: React.FC = () => {
    useEffect(() => {
        localStorage.removeItem('token');
    }, []);

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 仓库状态
    const {
        user: { userInfo },
    } = useSelector((state: StoreState) => state);
    const isAdmin = useSelector(
        (state: StoreState) => state.user.userInfo?.isAdmin
    );
    const username = useSelector(
        (state: StoreState) => state.user.userInfo?.username
    );

    // 仓库任务
    const dispatch: StoreDispatch = useDispatch();

    const okLogin = Object.keys(userInfo!).length;
    console.log('userInfo', userInfo);
    console.log('isAdmin', isAdmin);
    console.log('username', username);
    console.log(okLogin);

    const onFinish = async (values: loginData) => {
        messageApi
            .open({
                type: 'loading',
                content: '正在登录..',
                duration: 2,
            })
            .then(
                async () =>
                    // 发送登录请求
                    await dispatch(
                        toLoginAction({
                            username: values.username,
                            password: values.password,
                        })
                    )
            );
        setTimeout(() => {
            if (Object.keys(userInfo!).length >= 0) {
                messageApi.open({
                    type: 'success',
                    content: '登录成功!',

                    onClose() {
                        navigate('/home');
                    },
                });

                return;
            } else {
                messageApi.open({
                    type: 'error',
                    content: '登录失败!',
                });
            }
        }, 2000);
    };

    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    return (
        <div className="login_container" style={styles.login}>
            {contextHolder}
            <div className="title_big">Ant Design后台管理系统 </div>
            <div className="login_panel">
                <Form
                    name="basic"
                    labelCol={{ span: 0 }}
                    wrapperCol={{ span: 24 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        name="username"
                        rules={[
                            { required: true, message: '请输入用户名!' },
                            //   ({ getFieldValue }) => ({
                            //     // validator(_, value) {
                            //     //     if (value === 'admin') {
                            //     //         return Promise.resolve();
                            //     //     }
                            //     //     return Promise.reject(
                            //     //         new Error('用户名不存在!')
                            //     //     );
                            //     // },
                            //   }),
                        ]}
                    >
                        <Input
                            prefix={<UserOutlined />}
                            placeholder="用户名"
                            autoComplete="off"
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password
                            prefix={<LockOutlined />}
                            placeholder="密码"
                        />
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{ span: 24 }}
                        name="remember"
                        valuePropName="checked"
                    >
                        <Checkbox>记住密码</Checkbox>
                        <Button
                            type="link"
                            htmlType="button"
                            style={{ float: 'right' }}
                        >
                            忘记密码？
                        </Button>
                    </Form.Item>

                    <Form.Item wrapperCol={{ span: 24 }}>
                        <Button type="primary" htmlType="submit" block>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    );
};

export default Login;
